{extend name="base" /}
{block name="head"}
{/block}
{block name='content'}
<div class="layui-card" id="view_tpl1"></div>
<div class="layui-card">
    <div class="layui-tab layui-tab-brief" lay-filter="doc">
        <ul class="layui-tab-title">
            <li class="layui-this" lay-id="detail">接口详情</li>
            <li lay-id="debug">在线调试</li>
        </ul>
        <div class="layui-tab-content">
            <div class="layui-tab-item layui-show">
                <div id="view_tpl2" class="overflow"></div>
            </div>
            <div class="layui-tab-item">
                <div id="view_tpl3" class="overflow"></div>
            </div>
        </div>
    </div>
</div>
<script type="text/html" id="tpl1">
    <div class="layui-card-header" style="font-size: 16px">
        <blockquote class="layui-elem-quote">{{ d.title }}</blockquote>
    </div>
    <div style="background-color: #F2F2F2;margin-top:20px">
        <div class="layui-card-body">
                接口描述：{{ d.desc}}
        </div>
    </div>
</script>
<script type="text/html" id="tpl2">
    <table class="layui-table">
        <colgroup>
            <col width="100">
            <col>
        </colgroup>
        <tbody>
            <tr>
                <td>接口地址</td>
                <td><span>{{ d.url }}</span> <i class="copy-btn layui-icon layui-icon-form"></i></td>
            </tr>
            <tr>
                <td>后台方法</td>
                <td><span>{{ d.href }}</span> <i class="copy-btn layui-icon layui-icon-form"></i></td>
            </tr>
            <tr>
                <td>请求方式</td>
                <td>{{ d.method ? d.method : '-' }}</td>
            </tr>
            <tr>
                <td>接口版本</td>
                <td>{{ d.version ? d.version : '-' }}</td>
            </tr>
            <tr>
                <td>开发人员</td>
                <td>{{ d.author ? d.author : '-' }}</td>
            </tr>


            {{# if(d.param){ }}
            <tr>
                <td>请求参数</td>
                <td>
                    <table class="layui-table">
                        <colgroup>
                            <col width="100">
                            <col>
                        </colgroup>
                        <thead>
                            <tr>
                                <th>名称</th>
                                <th>类型</th>
                                <th>默认值</th>
                                <th>验证规则</th>
                                <th>说明</th>
                            </tr>
                        </thead>
                        <tbody>
                            {{# layui.each(d.param,function(k,v){ }}
                            <tr>
                                <td>{{ v.name }}</td>
                                <td>{{ v.type }}</td>
                                <td>{{ v.default }}</td>
                                <td>{{ v.valid }}</td>
                                <td>{{ v.desc }}</td>
                            </tr>
                            {{# }); }}
                        </tbody>

                    </table>
                </td>
            </tr>
            {{# } }} {{# if(d.return){ }}
            <tr>
                <td>响应参数</td>
                <td>
                    <table class="layui-table">
                        <colgroup>
                            <col width="100">
                            <col>
                        </colgroup>
                        <thead>
                            <tr>

                                <th>名称</th>
                                <th>类型</th>
                                <th>默认值</th>
                                <th>说明</th>
                            </tr>
                        </thead>
                        <tbody>
                            {{# layui.each(d.return,function(k,v){ }}
                            <tr>
                                <td>{{ v.name }}</td>
                                <td>{{ v.type }}</td>
                                <td>{{ v.default }}</td>
                                <td>{{ v.desc }}</td>
                            </tr>
                            {{# }); }}
                        </tbody>
                    </table>
                </td>
            </tr>
            {{# } }}
        </tbody>
    </table>
</script>
<script type="text/html" id="tpl3">
    <div class="layui-form layui-form-pane">
        <div class="layui-form-item">
            <label class="layui-form-label">接口地址</label>
            <div class="layui-input-block">
                {{# if(d.method == 'api'){ }}
                <input type="url" name="url" required readonly="readonly" autocomplete="off" class="layui-input" value="{{ d.href ? d.href : ''}}"> {{# }else{ }}
                <input type="url" name="url" required lay-verify="url" placeholder="请输入接口地址" autocomplete="off" class="layui-input" value="{{ d.url ? d.url : ''}}"> {{# } }}
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">请求方式</label>
            <div class="layui-input-inline">
                <select name="method" lay-verify="required">
                    {{# if(d.method == 'api'){ }}
                        <option value="API" selected}}>API</option>
                    {{# }else{ }}
                        {{# layui.each(['GET','POST','PUT','DELETE'],function(index,item){ }}
                        <option value="{{ item }}"
                                {{# if(item.trim()== d.method.trim()){ }}selected{{# } }}>{{ item }}
                        </option>
                        {{# }); }}
                    {{# } }}
                </select>
            </div>
            <label class="layui-form-label">请求类型</label>
            <div class="layui-input-inline">
                <select name="requestType" lay-verify="required">
                    {{# layui.each(['JSON','HTML','XML','SCRIPT','JSONP','TEXT'],function(index,item){ }}
                    <option value="{{ item }}"
                            {{# if(item.trim()== 'JSON'){ }}selected{{# } }}>{{ item }}
                    </option>
                    {{# }); }}
                </select>
            </div>
        </div>
        
        <div class="layui-form-item layui-form-text">
            <label class="layui-form-label">请求头部
                <span style="float: right;z-index: 999;position: relative;">
                    <button class="layui-btn layui-btn-xs" data-type="add" data-field="header" type="button">添加一行</button>
                </span>
                <span style="float: right;z-index: 999;position: relative;margin-right: 20px;">
                    <button class="layui-btn layui-btn-xs" data-type="zk" data-field="header" type="button">展开</button>
                </span>
            </label>
            <div class="layui-input-block" id="zk_info" style="display: none;">
                <table class="layui-table">
                    <colgroup>
                        <col width="100">
                        <col>
                    </colgroup>
                    <thead>
                        <tr>
                            <th>参数</th>
                            <th>参数值</th>
                            <th>操作</th>
                        </tr>
                    </thead>
                    <tbody>
                        {{# if(d.is_header == 1){ }} {{# layui.each(d._header,function(index,item){ }}
                        <tr>
                            <td><input name="header[name][]" type="text" disabled class="layui-input" value="{{ index }}">
                            </td>
                            <td><input name="header[value][]" type="text" class="layui-input" value="{{ item }}"></td>
                            <th>
                                <button class="layui-btn layui-btn-danger layui-btn-xs" type="button" data-type="del">删除
                            </button>
                            </th>
                        </tr>
                        {{# }); }} {{# }; }}
                    </tbody>
                </table>
            </div>
        </div>
        <div class="layui-form-item layui-form-text">
            <label class="layui-form-label">请求参数
                <span style="float: right;z-index: 999;position: relative;">
                    <button class="layui-btn layui-btn-xs" type="button" data-type="add" data-field="params">添加一行</button>
                </span>
            </label>
            <div class="layui-input-block">

                <table class="layui-table">
                    <colgroup>
                        <col width="200">
                        <col>
                    </colgroup>
                    <thead>
                        <tr>
                            <th>参数</th>
                            <th>参数值</th>
                            <th>操作</th>
                        </tr>
                    </thead>
                    <tbody>
                        {{# if(d.is_params == 1){ }} {{# layui.each(d._params,function(index,item){ }}
                        <tr>
                            <td><input name="params[name][]" type="text" disabled class="layui-input" value="{{ index }}">
                            </td>
                            <td><input name="params[value][]" type="text" class="layui-input" value="{{ trim(item['default']) == '' ? '' : item['default'] }}"></td>
                            <th>
                                <button class="layui-btn layui-btn-danger layui-btn-xs" type="button" data-type="del">删除
                            </button>
                            </th>
                        </tr>
                        {{# }); }} {{# }; }} {{# if(d.param){ }} {{# layui.each(d.param,function(index,item){ }}
                        <tr>
                            <td><input name="params[name][]" type="text" class="layui-input" value="{{ item['name'] }}"></td>
                            <td><input name="params[value][]" type="text"  {{ item.valid  == 'YES' ? 'required  lay-verify="required"' : '' }} class="layui-input" value="{{ trim(item['default']) == '' ? '' : item['default'] }}"></td>
                            <td>
                                <button class="layui-btn layui-btn-danger layui-btn-xs" type="button" data-type="del">删除
                            </button>
                            </td>
                        </tr>

                        {{# }); }} {{# } }}
                    </tbody>
                </table>

                <!-- <div style="text-align: center;">
                    <button class="layui-btn layui-btn-normal layui-btn-sm" type="button" data-type="add" data-field="params">添加一行
                    </button>
                </div> -->
            </div>
        </div>
        <div class="layui-form-item">
            <div class="layui-input-block">
                <button class="layui-btn" lay-submit lay-filter="debug">立即提交</button>
                <button type="reset" class="layui-btn layui-btn-primary">重置</button>
            </div>
        </div>
    </div>
</script>

<div class="layui-card">
    <div class="layui-card-header">温馨提示</div>
    <div class="layui-card-body">
        此文档是由系统自动生成，如发现错误或疑问请告知开发人员及时修改
    </div>
</div>

{/block}
{block name='js'}
<script>
    function trim(str) {
        return str.replace(/(^\s*)|(\s*$)/g, "").replace(/&nbsp;/ig, "").replace(/null/ig, "");
    }
    layui.use(['laytpl', 'jquery', 'form', 'layer'], function () {
        var laytpl = layui.laytpl,
            form = layui.form,
            layer = layui.layer,
            $ = layui.jquery;
        $.get(window.location.href, function (response) {
            if (response.code == 200) {
                render(tpl1.innerHTML, 'view_tpl1', response.data);
                render(tpl2.innerHTML, 'view_tpl2', response.data);
                render(tpl3.innerHTML, 'view_tpl3', response.data);
            }
        });

        function render(tpl, _view, data) {
            var view = document.getElementById(_view);
            laytpl(tpl).render(data, function (html) {
                view.innerHTML = html;
            })
            form.render();
        }
        $('body').on('click', '.copy-btn', function () {
            let val = $(this).prev().text();
            let input = '<input type="hidden" data-clipboard-text="' + val + '">';
            let $input = $(input);
            var clipboard = new Clipboard($input[0]);
            clipboard.on('success', function (e) {
                layer.msg('已复制', { 'icon': 6, time: 1000 });
            });
            $input.trigger('click');
        });
        var action = {
            add: function () {
                var field = this.data('field')
                this.parents('.layui-form-item').find('.layui-input-block').find('table tbody').append("<tr>\n" +
                    "                        <td><input name='" + field + "[name][]' type=\"text\" class=\"layui-input\" value=''></td>\n" +
                    "                        <td><input name='" + field + "[value][]' type=\"text\" class=\"layui-input\" value=''></td>\n" +
                    "                        <td>\n" +
                    "                            <button class=\"layui-btn layui-btn-danger layui-btn-xs\"\n" +
                    "                                    data-type=\"del\" \n" +
                    "                                    type=\"button\">删除\n" +
                    "                            </button>\n" +
                    "                        </td>\n" +
                    "                    </tr>");
            },
            del: function () {
                this.parents('tr').remove();
            },
            zk: function () {
                if ($('#zk_info').css('display') == 'none') {
                    $('#zk_info').css("display", 'block');
                    $(this).text('收缩');
                } else {
                    $('#zk_info').css("display", 'none');
                    $(this).text('展开');
                }
            }
        }

        $('body').delegate('button', 'click', function () {
            var type = $(this).data('type');
            action[type] && action[type].call($(this));
        });


        // 格式化对象输出
        function writeHtml(obj1) {
            var obj = apidoc_isJson(obj1);
            if (!obj) {
                obj = cnicdoe(obj);
                obj = apidoc_isJson(obj);
                if (!obj) {
                    obj = obj.replace(/(s*?{s*?|s*?,s*?)(['"])?([a-zA-Z0-9_]+)(['"])?:/g, '$1"$3":');
                    obj = JSON.parse(obj);
                }
            }
            return obj;
        }
        // 判断是否是json数据
        function apidoc_isJson(str) {
            if (typeof (str) === 'string') {
                try {
                    var obj = JSON.parse(str);
                    if (typeof (obj) === 'object' && obj) {
                        return obj;
                    } else {
                        return false;
                    }
                } catch (e) {
                    return false;
                }
            }
            return str;
        }
        // 判断字符是否为汉字，
        function isChinese(s) {
            return /[\u4e00-\u9fa5]/.test(s);
        }
        function cnicdoe(str) {
            if (!str) {
                return;
            }
            var unicode = '';
            for (var i = 0; i < str.length; i++) {
                var temp = str.charAt(i);
                if (isChinese(temp)) {
                    unicode += '\\u' + temp.charCodeAt(0).toString(16);
                }
                else {
                    unicode += temp;
                }
            }
            return unicode;
        }

        var htmlJson;
        form.on('submit(debug)', function (data) {
            var index = layer.load(0, {
                shade: false
            }); //0代表加载的风格，支持0-2
            let headers = {};
            headers = JSON.parse(localStorage.getItem('header'));
            $.ajax({
                url: "/{$route_prefix}/format_params",
                type: 'POST',
                // headers: headers,
                data: data.field,
                success: function (response) {
                    if (headers) {
                        for (let key in headers) {
                            response.data.header[key] = response.data.header[key] || headers[key];
                        }
                    }
                    if (data.field.method != 'API') {
                        $.ajax({
                            url: data.field.url,
                            type: data.field.method,
                            // headers: headers ,
                            //合并header
                            headers: response.data.header,
                            data: response.data.params,
                            datatype: data.field.requestType,
                            complete: function (XHR) {
                                layer.close(layer.index);
                                var html = "";
                                htmlJson = XHR.responseJSON == undefined ? XHR.responseText : XHR.responseJSON;
                                if (XHR.readyState == 4 && (XHR.status == 200)) {
                                    html = '<div class="code-json layui-form" lay-filter="formTest">'
                                        + '<div class="code-json-btn"><input type="checkbox" name="collapsed" lay-filter="filter" lay-skin="switch" lay-text="折叠|展开" checked></div>'
                                        + '<div class="code-json-btn"><input type="checkbox" name="withQuotes" lay-filter="filter" lay-skin="switch" lay-text="有引号|无引号" checked></div>'
                                        + '<div class="code-json-btn"><a id="saves" href="jsvascript:;" class="layui-btn layui-btn-sm">保存到本地</a></div>'
                                        + '</div><pre id="mier-code"></pre>';
                                } else {
                                    html = XHR.responseText;
                                }
                                layer.open({
                                    type: 1,
                                    title: '响应数据',
                                    offset: 'auto',
                                    shade: false,
                                    area: ['50%', '80%'],
                                    skin: 'layui-layer-molv',
                                    maxmin: true,
                                    content: html,
                                    success: function (obj) {
                                        let $this = obj.children('div.layui-layer-content').children('pre');
                                        if (!apidoc_isJson(htmlJson)) {
                                            $this.html(htmlJson);
                                        } else {
                                            $this.jsonViewer(writeHtml(htmlJson));
                                        }
                                        $(window).resize();
                                        form.render()
                                    }
                                });
                            }
                        })
                    }
                }
            });
            return false;
        });
        form.on('switch(filter)', function (obj) {
            var data = form.val("formTest");
            var arr = {
                collapsed: data.collapsed ? false : true
                , withQuotes: data.withQuotes ? false : true
                , withLinks: false
            };
            let $this = $(this).parents('.layui-form').siblings('pre');
            $this.jsonViewer(writeHtml(htmlJson), arr);
            $(window).resize();
            form.render();
        });
        $('body').on('click', '#saves', function () {
            saveJSON();
        });
        //json文件保存到本地
        function saveJSON() {
            var data = htmlJson;
            var d = new Date();
            var filename = d.Format("yyyy-MM-dd hh:mm:ss") + '.json';
            if (!data) {
                alert('data is null');
                return;
            }
            if (!filename) filename = 'json.json'
            if (typeof data === 'object') {
                data = JSON.stringify(data, undefined, 4)
            }
            var blob = new Blob([data], { type: 'text/json' });
            var e = document.createEvent('MouseEvents');
            var a = document.createElement('a');
            a.download = filename;
            a.href = window.URL.createObjectURL(blob);
            a.dataset.downloadurl = ['text/json', a.download, a.href].join(':');
            e.initMouseEvent('click', true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
            a.dispatchEvent(e);
        }
        Date.prototype.Format = function (fmt) { // author: meizz
            var o = {
                "M+": this.getMonth() + 1, // 月份
                "d+": this.getDate(), // 日
                "h+": this.getHours(), // 小时
                "m+": this.getMinutes(), // 分
                "s+": this.getSeconds(), // 秒
                "q+": Math.floor((this.getMonth() + 3) / 3), // 季度
                "S": this.getMilliseconds() // 毫秒
            };
            if (/(y+)/.test(fmt))
                fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
            for (var k in o)
                if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
            return fmt;
        }
    });
</script>
{/block}